package com.cyz.api.imagesearch.sub;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.cyz.api.imagesearch.model.ImageSearchResult;
import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;

import java.util.List;
import java.util.Map;

/**
 * 获取图片列表字典
 */
public class GetImageList {

    public static List<ImageSearchResult> getImageList(String url){
        // 发送请求，获取图片列表信息
        HttpResponse response = HttpUtil.createGet(url).execute();

        // 判断是否响应成功
        if (response.getStatus() != HttpStatus.HTTP_OK){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取图片列表失败");
        }

        // 响应成功解析返回的信息
        String body = response.body();

        Map<String, Object> bodyMap = JSONUtil.toBean(body, Map.class);

        if (!bodyMap.containsKey("data")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片列表获取失败");
        }

        Map<String, Object> dataMap = (Map<String, Object>) bodyMap.get("data");

        if (!dataMap.containsKey("list")){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片列表获取失败");
        }

        return JSONUtil.toList((JSONArray)dataMap.get("list"), ImageSearchResult.class);
    }


    public static void main(String[] args) {
        List<ImageSearchResult> imageList = getImageList("https://graph.baidu.com/ajax/pcsimi?carousel=503&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&inspire=general_pc&limit=30&next=2&render_type=card&session_id=3763688788953230572&sign=12149293acedd5d1ca97501753177831&tk=2b835&tpl_from=pc");
        System.out.println(imageList);
    }
}
